package io.hepu.robotize.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.hepu.robotize.IConstant;
import io.hepu.robotize.interceptor.AuthzInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

@Configuration
public class MvcConfiguration implements WebMvcConfigurer {
    @Resource
    private AuthzInterceptor authzInterceptor;
    @Resource
    private ShiroProperties shiroProperties;

    // Interceptors can be registered below
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authzInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(shiroProperties.getWhitelist());
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/MP_verify_*").addResourceLocations("classpath:/static/");
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // Remove the old converter.
        converters.removeIf(c -> c instanceof MappingJackson2HttpMessageConverter);
        // Initialize a new converter and append.
        converters.add(new MappingJackson2HttpMessageConverter(jackson2ObjectMapper()));
    }

    /**
     * ObjectMapper provides functionality for reading and writing JSON,
     * either to and from basic POJOs (Plain Old Java Objects),
     * or to and from a general-purpose JSON Tree Model (JsonNode),
     * as well as related functionality for performing conversions.
     *
     * @return ObjectMapper
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jackson2ObjectMapper() {
        SimpleDateFormat format = new SimpleDateFormat(IConstant.DATEFORMAT);
        TimeZone timeZone = TimeZone.getTimeZone(IConstant.TIMEZONE);
        format.setTimeZone(timeZone);

        return new Jackson2ObjectMapperBuilder()
                .serializationInclusion(JsonInclude.Include.NON_NULL)
                .timeZone(timeZone)
                .dateFormat(format)
                .build();
    }
}
